//
//  LoginVC.m
//  Tunnel
//
//  Created by wbb on 2025/5/30.
//

#import "LoginVC.h"
#import "HomeViewController.h"
#import "RSAPublicKeyEncryptor.h"
#import "JPUSHService.h"
@interface LoginVC ()
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (nonatomic, strong) UITextField * accountTF;
@property (nonatomic, strong) UITextField * pwdTF;
@property (nonatomic, copy) NSString * accountStr;
@property (nonatomic, copy) NSString * pwdStr;
@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.contentView.backgroundColor = [UIColor clearColor];
    [self initUI];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)initUI {
    UILabel *accontLab = [[UILabel alloc] init];
    accontLab.frame = CGRectMake(16.5,172.5,27,13);
    accontLab.numberOfLines = 0;
    [self.contentView addSubview:accontLab];
    
    [accontLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.offset(30);
    }];

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"账号" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang SC" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:42/255.0 green:42/255.0 blue:42/255.0 alpha:1.0]}];

    accontLab.attributedText = string;
    
    
    
    UIView *tfBgView = [[UIView alloc] init];
    tfBgView.backgroundColor = [UIColor colorWithRed:232/255.0 green:240/255.0 blue:255/255.0 alpha:1];
    tfBgView.layer.cornerRadius = 4;
    [self.contentView addSubview:tfBgView];
    [tfBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.equalTo(accontLab.mas_bottom).offset(10);
        make.right.offset(-16);
        make.height.offset(44);
    }];
   
    UITextField *accontTf = [[UITextField alloc] init];
    accontTf.placeholder = @"请输入账号";
    [accontTf addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [tfBgView addSubview:accontTf];
    self.accountTF = accontTf;
    [accontTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.right.offset(-15);
        make.centerY.offset(0);
        make.height.offset(30);
    }];

    
    
    UILabel *pwdLab = [[UILabel alloc] init];
    pwdLab.frame = CGRectMake(16.5,172.5,27,13);
    pwdLab.numberOfLines = 0;
    [self.contentView addSubview:pwdLab];
    
    [pwdLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.equalTo(tfBgView.mas_bottom).offset(20);
    }];

    NSMutableAttributedString *string1 = [[NSMutableAttributedString alloc] initWithString:@"密码" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang SC" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:42/255.0 green:42/255.0 blue:42/255.0 alpha:1.0]}];

    pwdLab.attributedText = string1;
    
    
    
    UIView *pwdTfBgView = [[UIView alloc] init];
    pwdTfBgView.backgroundColor = [UIColor colorWithRed:232/255.0 green:240/255.0 blue:255/255.0 alpha:1];
    pwdTfBgView.layer.cornerRadius = 4;
    [self.contentView addSubview:pwdTfBgView];
    [pwdTfBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.equalTo(pwdLab.mas_bottom).offset(10);
        make.right.offset(-16);
        make.height.offset(44);
    }];
   
    UITextField *pwdTf = [[UITextField alloc] init];
    pwdTf.placeholder = @"请输入密码";
    pwdTf.secureTextEntry = YES;
    pwdTf.autocapitalizationType = UITextAutocapitalizationTypeNone; // 关闭自动大写
    pwdTf.autocorrectionType = UITextAutocorrectionTypeNo; // 关闭自动修正
    [pwdTf addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [pwdTfBgView addSubview:pwdTf];
    self.pwdTF = pwdTf;
    [pwdTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.right.offset(-15);
        make.centerY.offset(0);
        make.height.offset(30);
    }];
    
    
    UIButton *logBtn = [UIButton buttonWithTitle:@"确定" titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16] target:self action:@selector(goLogin)];
    logBtn.backgroundColor = hexColor(226CFE);
    logBtn.cornerRadius = 4;
    [self.contentView addSubview:logBtn];
    [logBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.height.offset(44);
        make.top.equalTo(pwdTfBgView.mas_bottom).offset(35);
    }];
}
- (void)textChange:(UITextField *)tf {
    NSLog(@"%@",tf.text);
    if(tf == self.accountTF) {
        self.accountStr = tf.text;
    }else {
        self.pwdStr = tf.text;
    }
}
- (void)goLogin {
//    self.accountStr = @"rccs";
//    self.pwdStr = @"rc@CS123456";
    
    if([TYGlobal isBlankString:self.accountStr]){
        [MBProgressHUD promptMessage:@"账号不能为空" inView:self.view];
        return;
    }
    if([TYGlobal isBlankString:self.pwdStr]){
        [MBProgressHUD promptMessage:@"密码不能为空" inView:self.view];
        return;
    }
    
    
    
//    RSAPublicKeyEncryptor *encryptor = [[RSAPublicKeyEncryptor alloc] initWithPublicKeyBase64:publicPwd];
    NSString *encryptedBase64 = [self encryptPassword:self.pwdStr];//[encryptor encryptString:self.pwdStr];
    NSLog(@"加密后: %@", encryptedBase64);
    kWEAK_SELF;
    [TYNetWorkTool postRequest:TYLoginAPI parameters:@{
        @"password":encryptedBase64,
        @"username":self.accountStr?:@""
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        NSLog(@"%@",data);
        if(success) {
            [WDUtil setInfo:data[@"token"] forKey:TY_TOKEN];
            [WDUtil setInfo:self.pwdStr forKey:TY_PASSWORD];
            [WDUtil setInfo:self.accountStr forKey:TY_USERNAME];

            [weakSelf toHome];
            
            [WDGlobal shareInstance].uuid = [[self generateUniqueNumberID] integerValue];
            [JPUSHService setAlias:data[@"dataCenterUserInfo"][@"userCode"] completion:nil seq:[WDGlobal shareInstance].uuid];
        }else {
            [MBProgressHUD promptMessage:msg?:@"登录失败" inView:self.view];
        }
        
        
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];


}
- (NSString *)generateUniqueNumberID {
    // 1. 生成标准 UUID（如："E621E1F8-C36C-495A-93FC-0C247A3E6E5F"）
    NSString *uuid = [[NSUUID UUID] UUIDString];
    
    // 2. 移除 UUID 中的非数字字符
    NSString *numberString = [uuid stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, uuid.length)];
    
    // 3. 若长度不足，补充随机数字（确保长度足够，降低重复概率）
    if (numberString.length < 16) {
        NSUInteger needLength = 16 - numberString.length;
        for (NSUInteger i = 0; i < needLength; i++) {
            numberString = [numberString stringByAppendingString:[NSString stringWithFormat:@"%d", arc4random_uniform(10)]];
        }
    }
    
    return numberString;
}
- (void)toHome {
    // 调用方式
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate setWindowAndRootViewController]; // 初始化窗口和根控制器
}

- (NSString *)encryptPassword:(NSString *)password {
    NSLog(@"%@",publicKeyPEM);
    RSAPublicKeyEncryptor *cryptor = [[RSAPublicKeyEncryptor alloc] initWithPublicKeyPEM:publicKeyPEM];
    return [cryptor encryptString:password];
}
@end
